package com.tao.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.tao.common.to.SkuReductionTo;
import com.tao.common.to.SpuBoundsTo;
import com.tao.common.utils.R;
import com.tao.gulimall.product.entity.*;
import com.tao.gulimall.product.fegin.CouponFeginService;
import com.tao.gulimall.product.service.*;
import com.tao.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.common.utils.PageUtils;
import com.tao.common.utils.Query;

import com.tao.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeginService couponFeginService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * TODO 日后需要针对各种出现的问题进行处理
     * 保存
     * @param spuSaveVo
     */
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1. 保存spu基本信息, 对应 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        //2. 保存spu 描述图片, 对应 psm_spu_info_desc
        List<String> desc = spuSaveVo.getDecript();
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(spuInfoEntity.getId());
        infoDescEntity.setDecript(String.join(",",desc));
        spuInfoDescService.saveSpuInfoDesc(infoDescEntity);

        //3. 保存spu 图片集, 对应 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4. 保存spu的规格参数, 对应 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity attrValue = new ProductAttrValueEntity();
            attrValue.setSpuId(spuInfoEntity.getId());
            AttrEntity byId = attrService.getById(item.getAttrId());
            attrValue.setAttrName(byId.getAttrName());
            attrValue.setAttrId(item.getAttrId());
            attrValue.setQuickShow(item.getShowDesc());
            attrValue.setAttrValue(item.getAttrValues());
//            attrValue.setAttrSort();
            return attrValue;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(attrValueEntities);


        //5. 保存spu积分信息, 对应 gulimall_sms -> sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R saveSpuBounds = couponFeginService.saveSpuBounds(spuBoundsTo);
        if (saveSpuBounds.getCode() != 0){
            log.error("远程保存SPU 优惠信息失败");
        }

        //6. 保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus == null || skus.size() == 0){

        }else {
            skus.forEach(item->{
                // 先得到默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                //6.1 sku的基本信息, 对应 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);


                //6.2 sku的图片信息, 对应 pms_sku_images
                List<Images> itemImages = item.getImages();
                List<SkuImagesEntity> skuImagesEntities = itemImages.stream()
                        .filter(entity->{
                            // 返回 ture 表示是需要的, 返回false 表示是不需要的
                    return !StringUtils.isNullOrEmpty(entity.getImgUrl());
                })
                        .map(imgItem -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setDefaultImg(imgItem.getDefaultImg());
                    skuImagesEntity.setImgUrl(imgItem.getImgUrl());
//                    skuImagesEntity.setImgSort();
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3 保存sku的销售属性信息, 对应 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attrItem -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attrItem, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4 保存sku的优惠, 满减等信息, 对应 gulimall_sms -> sms_sku_loadder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                // 满减数量和满减多少元等信息, 如果都没有则不需要进行保存
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1 ){
                    R saveSkuReduction = couponFeginService.saveSkuReduction(skuReductionTo);
                    if(saveSkuReduction.getCode() != 0){
                        log.error("远程保存sku的优惠满减等信息失败");
                    }
                }
            });


        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

	@Override
	public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> lqw = new LambdaQueryWrapper<>();
        // 判断查询参数
        String key = (String) params.get("key");
        if(!StringUtils.isNullOrEmpty(key)){
            lqw.and(item->{
                item.like(SpuInfoEntity::getSpuName, key).or().eq(SpuInfoEntity::getId, key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isNullOrEmpty(status)){
           lqw.eq(SpuInfoEntity::getPublishStatus, status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isNullOrEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            lqw.eq(SpuInfoEntity::getBrandId, brandId);
        }
        String categoryId = (String) params.get("categoryId");
        if(!StringUtils.isNullOrEmpty(categoryId) && !"0".equalsIgnoreCase(categoryId)){
            lqw.eq(SpuInfoEntity::getCatalogId, categoryId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                lqw
        );

        return new PageUtils(page);

	}

}